var redis = require('../untils/redis');
const LIVE_LIST = 'LIVE_LIST';
const LIVE_EVENT = 'LIVE_EVENT';
const LIVE_STATS = 'LIVE_STATS';

const { sendMessage } = require('./socket');

const lastEvent = {};
const lastStats = {};

var isLike = function(a, b) {
	return JSON.stringify(a) === JSON.stringify(b);
}

var getList = function() {
	redis.get(LIVE_LIST, function(err, list) {
		list = JSON.parse(list);
		if (list && list.length > 0) {
			var idList = [];
			list.forEach(l => {
				getInfo(l);
				idList.push(l);
			})
			clearLast(idList);
		}
	})
}

var getInfo = function(id) {
	getEvent(id);
	getStats(id);
}

var getEvent = function(id) {
	redis.hmget(LIVE_EVENT, id, function(err, res) {
		if (res && res.toString()) {
			if (!isLike(lastEvent[id], res)) {
				sendMessage(id, res, 'event');
				lastEvent[id] = res;
			}
		}
	})
}

var getStats = function(id) {
	redis.hmget(LIVE_STATS, id, function(err, res) {
		if (res && res.toString()) {
			if (!isLike(lastStats[id], res)) {
				sendMessage(id, res, 'stats');
			}
		}
	})
}

var clearLast = function(list) {
	var keys = Object.keys(lastEvent);
	for (var i = 0; i < keys.length; i++) {
		var key = keys[i];
		if (list.indexOf(key) === -1) {
			delete lastEvent[key];
			delete lastStats[key];
		}
	}
}

var getAll = function() {
	redis.hgetall(LIVE_EVENT, function(err, res) {
		console.log(res);
	})
}

module.exports = {
	getInfo,
	getList,
	getAll
};